package com.jd.oneday.month3;

/**
 * 1.链表的创建
 * 2.删除链表节点
 */

public class Day06 {
    public static void main(String[] args) {
        LinkedListNodes linkedListNodes1 = new LinkedListNodes(78, "刘伟超", 5);
        LinkedListNodes linkedListNodes2 = new LinkedListNodes(85, "刘广超", 4);
        LinkedListNodes linkedListNodes3 = new LinkedListNodes(58, "刘满超", 14);
        LinkedListNodes linkedListNodes4 = new LinkedListNodes(45, "刘宇鹏", 7);

        SingleLinkedLists singleLinkedLists = new SingleLinkedLists();
        singleLinkedLists.add(linkedListNodes1);
        singleLinkedLists.add(linkedListNodes2);
        singleLinkedLists.add(linkedListNodes3);
        singleLinkedLists.add(linkedListNodes4);

        singleLinkedLists.dels(85);

        singleLinkedLists.lists();

    }
}


//定义一个管理链表的类
class SingleLinkedLists {
    private LinkedListNodes head = new LinkedListNodes(0, "", 0);

    //创建单链表
    public void add(LinkedListNodes h) {
        LinkedListNodes temp = head;
        while (true) {
            if (temp.next == null) {  //找到链表的最后一个节点
                break;
            }
            temp = temp.next;
        }
        temp.next = h;
    }

    //删除链表节点
    public void dels(int d) {

        LinkedListNodes temp = head;
        boolean flag = false;
        while (true) {
            if (temp.next == null) {  //已经到链表的最后
                break;
            }
            if (temp.next.id == d) {
                flag = true;
                break;
            }
            temp = temp.next;
        }
        if (flag == true) {
            temp.next = temp.next.next;  //将删除链表节点（temp.next）指向下一个链表节点，赋值给删除链表的前一个链表节点
        } else {
            System.out.println("没有找到这个id为" + d + "的节点");
        }
    }

    //遍历
    public void lists() {
        if (head.next == null) {
            System.out.println("这是一个空链表");
            return;
        }

        LinkedListNodes temp = head;

        while (true) {

            if (temp.next == null) {
                break;
            }

            temp = temp.next;
            System.out.println(temp);
        }
    }
}


//定义一个链表节点对象
class LinkedListNodes {

    int id;
    String name;
    int age;
    LinkedListNodes next;

    //构造器
    public LinkedListNodes(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "LinkedListNodes{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}